﻿using UnityEngine;
using System.Collections;

public class FindServer : MonoBehaviour {

    /*
     * This behavior scans its local subnet for a server. One should be alive when it's called,
     * but if it isn't, it'll just keep scanning until it finds one. 
     * 
     * ASSUMPTION: The server and the tablets will be on the same subnet (i.e. 192.168.1.*). 
    */

    private string localSubnetPrefix = string.Empty;

    private int checkIP = 0;
    private string serverIP = string.Empty;

    public int port = 0;

    private bool serverFound = false;
    private bool readyForTest = true;

    private System.Net.NetworkInformation.Ping serverPing = null;

	// Use this for initialization
	void Start () {

        string ipAddress = Network.player.ipAddress;
        localSubnetPrefix = ipAddress.Substring(0, ipAddress.LastIndexOf('.') + 1);
        print("Local subnet prefix is " + localSubnetPrefix);
        if (port == 0) port = GameObject.FindGameObjectWithTag("NetworkController").GetComponent<ConnectionManager>().port;
	}
	
	// Update is called once per frame
	void Update () {

        if (readyForTest && !serverFound)
        {
            readyForTest = false;

            checkIP++;
            if (checkIP > 255) checkIP = 0;

            serverIP = localSubnetPrefix + checkIP.ToString();
            print("Scanning at " + serverIP);

            serverPing = new System.Net.NetworkInformation.Ping();
            if (serverPing.Send(serverIP, 30).Status == System.Net.NetworkInformation.IPStatus.Success) 
            {
                Network.Connect(serverIP, port);
            }
        }

	}

    void OnConnectedToServer()
    {
        serverFound = true;
        print("Connected to server at " + serverIP);
    }

    void OnFailedToConnect(NetworkConnectionError error)
    {
        print("Failed to connect to server at " + serverIP);
        readyForTest = true;
    }

    void OnGUI()
    {
        GUI.color = Color.white;
        if (!serverFound)
        {
            GUILayout.Label("Looking for server at " + serverIP);
        }
        else
        {
            GUILayout.Label("Server found at " + serverIP);
        }
    }

}
